/*
'  DotNetNuke -  http://www.dotnetnuke.com
'  Copyright (c) 2002-2011
'  by DotNetNuke Corporation
' 
'  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
'  documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
'  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
'  to permit persons to whom the Software is furnished to do so, subject to the following conditions:
' 
'  The above copyright notice and this permission notice shall be included in all copies or substantial portions 
'  of the Software.
' 
'  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
'  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
'  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
'  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
'  DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Globalization;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using DotNetNuke.Modules.Store.Admin;
using DotNetNuke.Modules.Store.Cart;
using DotNetNuke.Modules.Store.Components;
using DotNetNuke.Modules.Store.Customer;
using DotNetNuke.Modules.Store.Providers;
using DotNetNuke.Modules.Store.Providers.Address;

namespace DotNetNuke.Modules.Store.WebControls
{
	/// <summary>
	/// Summary description for CustomerOrders.
	/// </summary>
	public partial  class CustomerOrders : StoreControlBase, IStoreTabedControl
	{
		#region Private Members

        private static string CookieName = "DotNetNuke_Store_Portal_";
        private CustomerNavigation customerNav;
        private OrderController orderController;
        private IAddressProvider addressProvider;
        private string _Message = string.Empty;
        private string _OrderDateFormat = string.Empty;
        private NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
        private List<OrderStatus> orderStatusList;
        private ModuleSettings moduleSettings;
        private string productColumn;
        private bool canManageOrders = false;

		#endregion

        public bool ShowOrdersInStatus = false;
        public int OrderStatusID = Null.NullInteger;

		#region Web Form Designer generated code

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.grdOrders.ItemDataBound += new DataGridItemEventHandler(this.grdOrders_ItemDataBound);
            this.grdOrderDetails.ItemDataBound += new DataGridItemEventHandler(this.grdOrderDetails_ItemDataBound);
            this.lnkbtnSave.Click += new EventHandler(lnkbtnSave_Click);
            this.btnBack.Click += new EventHandler(btnBack_Click);
		}

		#endregion

		#region Events

		protected void Page_Load(object sender, System.EventArgs e)
		{
            // Read module settings
            moduleSettings = new ModuleSettings(ModuleId, TabId);
            // Init vars
            productColumn = moduleSettings.MainCart.ProductColumn.ToLower();
            if (StoreSettings.CurrencySymbol != string.Empty)
                LocalFormat.CurrencySymbol = StoreSettings.CurrencySymbol;
            _OrderDateFormat = Localization.GetString("OrderDateFormat", this.LocalResourceFile);
			customerNav = new CustomerNavigation(Request.QueryString);
			lblError.Text = "";  //Initialize the Error Label.
            pnlOrdersError.Visible = false;
            orderController = new OrderController();
            addressProvider = StoreController.GetAddressProvider(StoreSettings.AddressName);

            CheckUserRoles();

            if (ShowOrdersInStatus == true && OrderStatusID != Null.NullInteger)
            {
                plhGrid.Visible = true;
                plhForm.Visible = false;

                List<OrderInfo> orders = orderController.GetOrders(PortalId, OrderStatusID);

                if (orders.Count > 0)
                {
                    orderStatusList = orderController.GetOrderStatuses();
                    grdOrders.DataSource = orders;
                    grdOrders.DataBind();
                }
                else
                {
                    lblError.Text = Localization.GetString("NoOrdersFound", this.LocalResourceFile);
                    pnlOrdersError.Visible = true;
                    pnlOrders.Visible = false;
                    grdOrders.DataSource = null;
                    grdOrders.DataBind();
                }
            }
            else
            {
                if (customerNav.OrderID != Null.NullInteger)
                {
                    plhGrid.Visible = false;
                    plhForm.Visible = true;

                    if (customerNav.OrderID != 0)
                    {
                        lblEditTitle.Text = Localization.GetString("ViewDetails", this.LocalResourceFile);
                        ShowOrderDetails(customerNav.OrderID);
                    }
                }
                else
                {
                    if (customerNav.CustomerID == Null.NullInteger)
                        customerNav.CustomerID = UserId;
                    else if (canManageOrders == false && customerNav.CustomerID != UserId)
                    {
                        // Someone is trying to steal data
                        pnlOrders.Visible = false;
                        throw new Exception(Localization.GetString("Unexpected.Error", this.LocalSharedResourceFile));
                    }

                    if (canManageOrders == true || StoreSettings.AuthorizeCancel == true)
                        grdOrders.Columns[6].Visible = true;
                    else
                        grdOrders.Columns[6].Visible = false;

                    plhGrid.Visible = true;
                    plhForm.Visible = false;
                    DisplayCustomerOrders();
                }
            }
		}

		protected void grdOrders_ItemDataBound(object sender, DataGridItemEventArgs e)
		{
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                OrderInfo order = (OrderInfo)e.Item.DataItem;

                //Order Date
                Label lblOrderDateText = (Label)e.Item.FindControl("lblOrderDateText");
                lblOrderDateText.Text = order.OrderDate.ToString(_OrderDateFormat);

                //Order Status
                Label lblOrderStatusText = (Label)e.Item.FindControl("lblOrderStatusText");
                lblOrderStatusText.Text = GetOrderStatus(order.OrderStatusID);

                //Order Total
                Label lblOrderTotalText = (Label)e.Item.FindControl("lblOrderTotalText");
                lblOrderTotalText.Text = order.GrandTotal.ToString("C", LocalFormat);

                //Ship Date (Status Date)
                Label lblShipDateText = (Label)e.Item.FindControl("lblShipDateText");
                if (order.OrderStatusID > 1)
                    lblShipDateText.Text = order.ShipDate.ToString(_OrderDateFormat);
                else
                    lblShipDateText.Text = "";

                //Edit-Details link
                HyperLink lnkEdit = (HyperLink)e.Item.FindControl("lnkEdit");
                if (lnkEdit != null)
                {
                    customerNav.OrderID = order.OrderID;
                    customerNav.CustomerID = order.CustomerID;
                    lnkEdit.NavigateUrl = customerNav.GetNavigationUrl();
                }

                //Cancel link
                if (canManageOrders == true || StoreSettings.AuthorizeCancel == true)
                {
                    LinkButton lnkCancel = (LinkButton)e.Item.FindControl("lnkCancel");
                    if (lnkCancel != null)
                    {
                        if (order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingPayment
                            || order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingStock
                            || order.OrderStatusID == (int)OrderInfo.OrderStatusList.Paid)
                        {
                            lnkCancel.CommandArgument = order.OrderID.ToString();
                            lnkCancel.Click += new EventHandler(lnkCancel_Click);
                            lnkCancel.Enabled = true;
                        }
                        else 
                            lnkCancel.Enabled = false;
                    }
                }
            }
		}

        protected void lnkCancel_Click(object sender, EventArgs e)
        {
            int orderID;
            if (Int32.TryParse(((LinkButton)sender).CommandArgument, out orderID))
                CancelOrder(orderID);
        }

        protected void btnPayNow_Click(object sender, EventArgs e)
        {
            int orderID;
            if (Int32.TryParse(((Button)sender).CommandArgument, out orderID))
            {
                // Get order details
                List<OrderDetailInfo> details = orderController.GetOrderDetails(orderID);
                if (details != null)
                {
                    bool secureCookies = StoreSettings.SecureCookie;
                    // Populate cart with order details
                    foreach (OrderDetailInfo detail in details)
                        CurrentCart.AddItem(PortalId, secureCookies, detail.ProductID, detail.Quantity);
                    // Set cookie and redirect to checkout page
                    SetOrderIdCookie(orderID);
                    customerNav = new CustomerNavigation();
                    customerNav.PageID = "checkout";
                    Response.Redirect(customerNav.GetNavigationUrl(), true);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            int orderID;
            if (Int32.TryParse(((Button)sender).CommandArgument, out orderID))
                CancelOrder(orderID);
        }

        protected void grdOrderDetails_ItemDataBound(object sender, DataGridItemEventArgs e)
		{
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                OrderDetailInfo detail = (OrderDetailInfo)e.Item.DataItem;

                //Product Title
                Label lblModelName = (Label)e.Item.FindControl("Label1");
                if (lblModelName != null)
                {
                    string productTitle = null;
                    switch (productColumn)
                    {
                        case "modelnumber":
                            productTitle = detail.ModelNumber;
                            break;
                        case "modelname":
                            productTitle = detail.ModelName;
                            break;
                        case "producttitle":
                            productTitle = detail.ProductTitle;
                            break;
                    }
                    lblModelName.Text = productTitle;
                }

                //Unit Cost
                Label lblODPriceText = (Label)e.Item.FindControl("lblODPriceText");
                lblODPriceText.Text = detail.UnitCost.ToString("C", LocalFormat);

                //Extended Amount
                Label lblODSubtotalText = (Label)e.Item.FindControl("lblODSubtotalText");
                lblODSubtotalText.Text = detail.ExtendedAmount.ToString("C", LocalFormat);
            }
            
		}

        protected void editControl_EditComplete(object sender, EventArgs e)
		{
			customerNav.OrderID = Null.NullInteger;
			Response.Redirect(customerNav.GetNavigationUrl(), false);
		}

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            //Update the order status...
            OrderInfo Order = orderController.GetOrder(PortalId, customerNav.OrderID);
            
            if (Order != null)
            {
                int orderStatusID = Convert.ToInt32(ddlOrderStatus.SelectedValue);
                Order.OrderStatusID = orderStatusID;
                Order.Status = orderController.GetStatusText(orderStatusID);
                // Update Status Order
                orderController.UpdateOrder(Order.OrderID, Order.OrderDate, Order.OrderNumber, Order.ShippingAddressID, Order.BillingAddressID, Order.TaxTotal, Order.ShippingCost, true, Order.OrderStatusID, Order.CustomerID);

                // If order is paid, add User to Roles
                if (orderStatusID == 7)
                    orderController.AddUserToRoles(this.PortalId, Order);

                // If order is canceled
                if (orderStatusID == 6)
                {
                    if (StoreSettings.InventoryManagement == true)
                    {
                        // Update Stock Products
                        List<OrderDetailInfo> orderDetails = orderController.GetOrderDetails(Order.OrderID);
                        foreach (OrderDetailInfo detail in orderDetails)
                            orderController.UpdateStockQuantity(detail.ProductID, detail.Quantity);
                    }
                    // Remove User from Roles
                    orderController.RemoveUserFromRoles(this.PortalId, Order);
                }

                // Send email
                if (chkSendEmailStatus.Checked == true)
                {
                    string commentToCustomer = txtCommentToCustomer.Text;
                    if (string.IsNullOrEmpty(commentToCustomer) == false)
                        Order.CommentToCustomer = commentToCustomer;
                    SendOrderStatusChangeEmail(Order);
                }

                // Redirect to order list
                customerNav.OrderID = Null.NullInteger;
                Response.Redirect(customerNav.GetNavigationUrl(), false);
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            customerNav.OrderID = Null.NullInteger;
            Response.Redirect(customerNav.GetNavigationUrl(),  false);
        }

		#endregion

		#region Private Function

        private string GetOrderStatus(int orderStatusID)
        {
            if (orderStatusList == null)
                orderStatusList = orderController.GetOrderStatuses();

            string OrderStatusText = "";
            foreach (OrderStatus orderStatus in orderStatusList)
            {
                if (orderStatus.OrderStatusID == orderStatusID)
                {
                    OrderStatusText = orderStatus.OrderStatusText;
                    break;
                }
            }
            return OrderStatusText;
        }

        private void DisplayCustomerOrders()
        {
            // If the user is logged
            if (IsLogged == true)
            {
                List<OrderInfo> orders = orderController.GetCustomerOrders(PortalId, customerNav.CustomerID);

                if (orders.Count > 0)
                {
                    if (orderStatusList == null)
                        orderStatusList = orderController.GetOrderStatuses();
                    grdOrders.DataSource = orders;
                    grdOrders.DataBind();
                }
                else
                {
                    lblError.Text = Localization.GetString("NoOrdersFound", this.LocalResourceFile);
                    pnlOrdersError.Visible = true;
                    pnlOrders.Visible = false;
                }
            }
            else
            {
                lblError.Text = Localization.GetString("UserNotLogged", this.LocalResourceFile);
                pnlOrdersError.Visible = true;
                pnlOrders.Visible = false;
            }
        }

        private void SendOrderStatusChangeEmail(OrderInfo Order)
        {
            // Store admin
            string adminEmail = "";
            string adminSubjectEmail = "";
            string adminBodyEmail = "";
            // Customer
            string customerEmail = "";
            string customerSubjectEmail = "";
            string customerBodyEmail = "";

            // Get Store Currency Symbol
            if (string.IsNullOrEmpty(StoreSettings.CurrencySymbol) == false)
                Order.CurrencySymbol = StoreSettings.CurrencySymbol;

            // Get Order Date Format
            string orderDateFormat = Localization.GetString("OrderDateFormat", this.LocalResourceFile);
            if (string.IsNullOrEmpty(orderDateFormat) == false)
                Order.DateFormat = orderDateFormat;

            // Get Customer Email
            IAddressInfo billingAddress = GetAddress(Order.BillingAddressID, Order.CustomerID);
            customerEmail = billingAddress.Email;
            // Try to get email address from user account,
            // this could be required for older orders.
            if (string.IsNullOrEmpty(customerEmail) == true)
            {
                UserController userControler = new UserController();
                UserInfo user = userControler.GetUser(PortalId, Order.CustomerID);
                customerEmail = user.Email;
            }

            // Get Admin Email
            adminEmail = StoreSettings.DefaultEmailAddress;

            // Customer Order Email Template
            customerSubjectEmail = Localization.GetString("CustomerStatusChangedEmailSubject", this.LocalResourceFile);
            customerBodyEmail = Localization.GetString("CustomerStatusChangedEmailBody", this.LocalResourceFile);

            // Admin Order Email Template
            adminSubjectEmail = Localization.GetString("AdminStatusChangedEmailSubject", this.LocalResourceFile);
            adminBodyEmail = Localization.GetString("AdminStatusChangedEmailBody", this.LocalResourceFile);

            // Init Email Order Replacement Tokens
            EmailOrderTokenReplace tkEmailOrder = new EmailOrderTokenReplace();
            tkEmailOrder.StoreSettings = StoreSettings;
            tkEmailOrder.Order = Order;

            // Replace tokens
            customerSubjectEmail = tkEmailOrder.ReplaceEmailOrderTokens(customerSubjectEmail);
            customerBodyEmail = tkEmailOrder.ReplaceEmailOrderTokens(customerBodyEmail);
            adminSubjectEmail = tkEmailOrder.ReplaceEmailOrderTokens(adminSubjectEmail);
            adminBodyEmail = tkEmailOrder.ReplaceEmailOrderTokens(adminBodyEmail);

            try
            {
                // Send Customer Email
                Mail.SendMail(adminEmail, customerEmail, "", customerSubjectEmail, customerBodyEmail, "", Mail.IsHTMLMail(customerBodyEmail) == true ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");

                // Send Store Admin Email
                Mail.SendMail(adminEmail, adminEmail, "", adminSubjectEmail, adminBodyEmail, "", Mail.IsHTMLMail(adminBodyEmail) == true ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

		private void ShowOrderDetails(int OrderID)
		{
			// Get Order
			OrderInfo Order = orderController.GetOrder(PortalId, OrderID);

            // If Order exist and current user is authorized to see it
            if (Order != null && (Order.CustomerID == UserId || canManageOrders == true))
            {
                pnlOrderDetails.Visible = true;
                // Order Header
                lblOrderNumber.Text = Order.OrderID.ToString();
                lblOrderDate.Text = Order.OrderDate.ToString(_OrderDateFormat);
                // Order Status
                if (orderStatusList == null)
                    orderStatusList = orderController.GetOrderStatuses();
                string OrderStatusText = "";
                foreach (OrderStatus orderStatus in orderStatusList)
                {
                    if (orderStatus.OrderStatusID == Order.OrderStatusID)
                    {
                        if (Order.OrderStatusID > 1)
                            OrderStatusText = orderStatus.OrderStatusText + " - " + Order.ShipDate.ToString(_OrderDateFormat);
                        else
                            OrderStatusText = orderStatus.OrderStatusText;
                        break;
                    }
                }
                lblOrderStatus.Text = OrderStatusText;
                //Cancel button
                btnCancel.Visible = false;
                if (StoreSettings.AuthorizeCancel == true && canManageOrders == false)
                {
                    if (Order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingPayment
                        || Order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingStock
                        || Order.OrderStatusID == (int)OrderInfo.OrderStatusList.Paid)
                    {
                        btnCancel.CommandArgument = Order.OrderID.ToString();
                        btnCancel.Click += this.btnCancel_Click;
                        btnCancel.Visible = true;
                    }
                }
                //Pay Now button
                btnPayNow.Visible = false;
                if (StoreSettings.GatewayName != "EmailProvider")
                {
                    btnPayNow.Click += new EventHandler(btnPayNow_Click);
                    if (Order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingPayment)
                    {
                        btnPayNow.CommandArgument = Order.OrderID.ToString();
                        btnPayNow.Click += this.btnPayNow_Click;
                        btnPayNow.Visible = true;
                    }
                }
                // Billing Address
                IAddressInfo billingAddress = GetAddress(Order.BillingAddressID, Order.CustomerID);
                if (billingAddress != null)
                    lblBillTo.Text = FormatAddress(billingAddress, canManageOrders);
                else
                    lblBillTo.Text = string.Format(Localization.GetString("UserDeleted", this.LocalResourceFile), Order.CustomerID);
                // ShippingAddress
                if (Order.ShippingAddressID != Order.BillingAddressID)
                {
                    IAddressInfo shippingAddress = GetAddress(Order.ShippingAddressID, Order.CustomerID);
                    if (shippingAddress != null)
                        lblShipTo.Text = FormatAddress(shippingAddress, canManageOrders);
                    else
                        lblShipTo.Text = Localization.GetString("ShipToAddressNotAvailable", this.LocalResourceFile);
                }
                else
                    lblShipTo.Text = Localization.GetString("SameAsBilling", this.LocalResourceFile);
                // Get Order Details
                List<OrderDetailInfo> orderDetails = orderController.GetOrderDetails(OrderID);
                // If Order detail was found, display it
                if (orderDetails != null)
                {
                    plhForm.Visible = true;

                    // Bind Items to GridControl
                    grdOrderDetails.DataSource = orderDetails;
                    grdOrderDetails.DataBind();
                }
                else
                {
                    // otherwise display an error message
                    lblError.Text = Localization.GetString("DetailsNotFound", this.LocalResourceFile);
                    pnlOrdersError.Visible = true;
                    plhForm.Visible = false;
                }

                // Footer
                if (Order.ShippingCost == 0 && Order.TaxTotal == 0)
                {
                    trTotal.Visible = false;
                    trShipping.Visible = false;
                    trTax.Visible = false;
                }
                else
                {
                    // Total
                    lblTotal.Text = Order.OrderTotal.ToString("C", LocalFormat);
                    // Shipping Cost
                    if (Order.ShippingCost > 0)
                        lblPostage.Text = Order.ShippingCost.ToString("C", LocalFormat);
                    else
                        trShipping.Visible = false;
                    // Tax
                    if (Order.TaxTotal > 0)
                        lblTax.Text = Order.TaxTotal.ToString("C", LocalFormat);
                    else
                        trTax.Visible = false;
                }
                // Grand Total
                lblTotalIncPostage.Text = Order.GrandTotal.ToString("C", LocalFormat);

                // Status Management
                if (canManageOrders)
                {
                    OrderStatusManagement.Visible = true;

                    // Bind Order status list...
                    ddlOrderStatus.DataSource = orderStatusList;
                    ddlOrderStatus.DataTextField = "OrderStatusText";
                    ddlOrderStatus.DataValueField = "OrderStatusID";
                    ddlOrderStatus.DataBind();

                    // Select current status
                    ListItem currentStatus = ddlOrderStatus.Items.FindByValue(Order.OrderStatusID.ToString());
                    if (currentStatus != null)
                        currentStatus.Selected = true;
                }
                else
                    OrderStatusManagement.Visible = false;
            }
            else
                plhForm.Visible = false;
		}

        private void CheckUserRoles()
        {
            if (UserInfo.IsSuperUser || UserInfo.IsInRole("Administrators"))
                canManageOrders = true;
            else
            {
                if (StoreSettings.OrderRoleID != Null.NullInteger)
                {
                    RoleController roleController = new RoleController();
                    RoleInfo orderRole = roleController.GetRole(StoreSettings.OrderRoleID, PortalId);
                    if (UserInfo.IsInRole(orderRole.RoleName))
                        canManageOrders = true;
                }
            }
        }

        private IAddressInfo GetAddress(int addressID, int customerID)
        {
            IAddressInfo address = null;

            if (addressID == 0)
                address = addressProvider.GetRegistrationAddress(this.PortalId, customerID, "");
            else
                address = addressProvider.GetAddress(addressID);

            return address;
        }

        private string FormatAddress(IAddressInfo address, Boolean showEmail)
        {
            string formatedAddress = string.Empty;

            if (address != null)
            {
                string fullName = address.FirstName + " " + address.LastName;
                formatedAddress = "<i>" + fullName.Trim() + "</i><br />" +
                address.Address1 + (address.Address2 != null ? "<br />" + address.Address2 : "") + "<br />" +
                address.City + "<br />" + (address.RegionCode != null ? address.RegionCode + "<br />" : "") +
                address.PostalCode + "<br />" + address.Phone1 + (address.Phone2 != null ? "<br />" + address.Phone2 : "");

                if (showEmail == true)
                {
                    string userEmail = string.Empty;

                    if (address.UserID != UserInfo.UserID)
                    {
                        if (address.UserID == StoreSettings.ImpersonatedUserID)
                            userEmail = address.Email;
                        else
                        {
                            UserController controller = new UserController();
                            UserInfo userInfo = controller.GetUser(PortalId, address.UserID);

                            if (userInfo != null)
                                userEmail = userInfo.Membership.Email;
                        }
                    }
                    else
                        userEmail = UserInfo.Membership.Email;

                    if (userEmail != string.Empty)
                        formatedAddress += "<br />" + string.Format("<a href=\"mailto:{0}\">{0}</a>", userEmail);
                }
            }

            return formatedAddress;
        }

        private void CancelOrder(int orderID)
        {
            OrderInfo Order = orderController.GetOrder(PortalId, orderID);

            if (canManageOrders == true || Order.CustomerID == this.UserId)
            {
                // Update Status Order
                Order.OrderStatusID = (int)OrderInfo.OrderStatusList.Cancelled;
                Order.Status = orderController.GetStatusText(Order.OrderStatusID);
                orderController.UpdateOrder(Order.OrderID, Order.OrderDate, Order.OrderNumber, Order.ShippingAddressID, Order.BillingAddressID, Order.TaxTotal, Order.ShippingCost, true, Order.OrderStatusID, Order.CustomerID);

                if (StoreSettings.InventoryManagement == true)
                {
                    // Update Stock Products
                    List<OrderDetailInfo> orderDetails = orderController.GetOrderDetails(Order.OrderID);
                    foreach (OrderDetailInfo detail in orderDetails)
                        orderController.UpdateStockQuantity(detail.ProductID, detail.Quantity);
                }

                // Remove User from Roles
                orderController.RemoveUserFromRoles(PortalId, Order);

                // Send email
                SendOrderStatusChangeEmail(Order);
            }

            //Force a re-binding of the search grid
            customerNav.OrderID = Null.NullInteger;
            Response.Redirect(customerNav.GetNavigationUrl(), true);
        }

        private string CookieKey
        {
            get { return CookieName + PortalId.ToString(); }
        }

        private void SetOrderIdCookie(int OrderID)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieKey];
            if (cookie == null)
                cookie = new HttpCookie(CookieKey);
            string cookieValue;
            if (StoreSettings.SecureCookie == true && SymmetricHelper.CanSafelyEncrypt == true)
                cookieValue = SymmetricHelper.Encrypt(OrderID.ToString());
            else
                cookieValue = OrderID.ToString();
            cookie["OrderID"] = cookieValue;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

		#endregion

        #region IStoreTabedControl Members

        public string Title
        {
            get { return Localization.GetString("lblParentTitle", this.LocalResourceFile); }
        }

        #endregion
    }
}
